package com.mybatis.jpa.utils;

import org.apache.commons.lang3.StringUtils;

import javax.persistence.Column;
import javax.persistence.Id;
import java.lang.reflect.Field;

public class FieldFacade {

	private Field field;
	private Object obj;
	
	public FieldFacade(Field field, Object obj) {
		super();
		this.field = field;
		this.obj = obj;
	}
	
	public String getColumnName() {
		Column column = field.getAnnotation(Column.class);
		if (column == null) {
			return JpaStringUtils.humpToUnderline(field.getName());
		} else {
			return StringUtils.isNotBlank(column.name()) ? column.name() : JpaStringUtils.humpToUnderline(field.getName());
		}
	}
	
	public Field getField() {
		return field;
	}
	
	/**
	 * 获取对象的属性名称，封装Field.getName()方法
	 * @return 属性名
	 */
	public String getFieldName() {
		return field.getName();
	}
		
	public Class<?> getJavaType() {
		return field.getType();
	}
	
	/**
	 * 基本类型，int，long等于0，返回true
	 * @return
	 * @throws Exception 
	 */
	public boolean isNumEqNullOrEqZero() throws Exception {
		Object object = this.getFieldValue();
		String classType = this.getJavaType().getName();
		if (object == null) {
			return true;
		}
		if (("int".equalsIgnoreCase(classType) || (object instanceof Integer))) {
			return true;
		}
		if (("long".equalsIgnoreCase(classType) || (object instanceof Long))) {
			return true;
		}
		return false;
	}
	
	public boolean isId() {
		if (field.getAnnotation(Id.class) != null) {
			return true;
		}
		return false;
	}
	
	public Object getFieldValue() throws Exception {
		return field.get(obj);
	}
}
